package com.nus.iss.ad.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.CookieHandler;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;

import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy;
import android.util.Log;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;

public class JsonParser {

	public static final String URL = "http://10.10.2.223:8080/";
	private static CookieStore sCookieStore;

	public static boolean authenticatePost(String url, String data,String[] outJsonResult) {

		InputStream is = null;
		try {
			StrictMode.setThreadPolicy(ThreadPolicy.LAX);
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);
			
			httpPost.setEntity(new StringEntity(data));
			httpPost.setHeader("Accept", "application/json");
			httpPost.setHeader("Content-type", "application/json");
			// call the cookie thing
			// httpClient.setCookieStore(sCookieStore);
			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();

			//String cookieId = "";
			sCookieStore = ((AbstractHttpClient) httpClient)
					.getCookieStore();
			//List<Cookie> cookies = ((AbstractHttpClient) httpClient)
					///.getCookieStore().getCookies();
			
			/*for (Cookie cookie : cookies) {
				if (cookie.getName().equals("JSESSIONID")) {
					cookieId = cookie.getValue();
				}
			}
			*/

			is = httpEntity.getContent();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		outJsonResult[0]=readStream(is);

		if (sCookieStore.getCookies().size()>0 ) {
			return true;
		} else {
			return false;
		}
	}

	public static String getStream(String url) {
		InputStream is = null;
		try {
			
			StrictMode.setThreadPolicy(ThreadPolicy.LAX);
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(url);
			//HttpGet httpGet = new HttpGet("http://10.10.2.192:8080/api/test");
			httpClient.setCookieStore(sCookieStore);
			
			//httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.11 Safari/537.36");
			//User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.11 Safari/537.36
			//httpGet.setHeader("Accept", "*");
			//httpGet.setHeader("Accept-Encoding", "gzip,deflate,sdch");
			//httpGet.setHeader("Accept-Language", "en-GB,en-US;q=0.8,en;q=0.6,zh-CN;q=0.4");
			HttpResponse httpResponse = httpClient.execute(httpGet); 
			
			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();
			 
			
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return (readStream(is));
	}

	

	static String readStream(InputStream is) {
		StringBuilder sb = new StringBuilder();
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
				sb.append('\n');
			}
			is.close();
		} catch (Exception e) {
			Log.e("Buffer Error", "Error converting result " + e.toString());
		}
		return (sb.toString());
	}
	
	public static JSONObject getJSONFromJson(String json) {
		JSONObject jObj = null;
		try {
			jObj = new JSONObject(json);
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
		}
		return jObj;
	}

	public static JSONArray getJSONArrayFromJson(String json) {
		JSONArray jArray = null;
		try {
			jArray = new JSONArray(getStream(json));
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing array " + e.toString());
		}
		return jArray;
	}

	public static JSONObject getJSONFromUrl(String url) {
		JSONObject jObj = null;
		try {
			jObj = new JSONObject(getStream(url));
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
		}
		return jObj;
	}

	public static JSONArray getJSONArrayFromUrl(String url) {
		JSONArray jArray = null;
		try {
			jArray = new JSONArray(getStream(url));
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing array " + e.toString());
		}
		return jArray;
	}

	public static String postStream(String url, String data) {
		InputStream is = null;
		try {
			StrictMode.setThreadPolicy(ThreadPolicy.LAX);
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);
			httpPost.setEntity(new StringEntity(data));
			httpPost.setHeader("Accept", "application/json");
			httpPost.setHeader("Content-type", "application/json");
			// call the cookie thing
			httpClient.setCookieStore(sCookieStore);
			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return readStream(is);
	}
	
	public static JSONObject postStreamJSONObject(String url, Object data) {
		//Convert data to Json String
		Gson gson=new Gson();
		String jsonData=gson.toJson(data,data.getClass());
		
		//Post to server side
		String json=postStream(url, jsonData);
		
		//Convert result to JSONObject
		JSONObject jsonObject=getJSONFromJson(json);
		return jsonObject;
	}
	
	public static JSONArray postStreamJSONArray(String url, Object data) {
		//Convert data to Json String
		Gson gson=new Gson();
		String jsonData=gson.toJson(data,data.getClass());
		
		//Post to server side
		String json=postStream(url, jsonData);
		
		//Convert result to JSONArray
		JSONArray jsonArray=getJSONArrayFromJson(json);
		return jsonArray;
	}
	// / the below method will help in creating the cookie for the login
	@SuppressWarnings("unused")
	private static String invoke(HttpUriRequest request)
			throws ClientProtocolException, IOException {
		String result = null;
		DefaultHttpClient httpClient = new DefaultHttpClient();

		// restore cookie
		if (sCookieStore != null) {
			httpClient.setCookieStore(sCookieStore);
		}

		HttpResponse response = httpClient.execute(request);

		StringBuilder builder = new StringBuilder();
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				response.getEntity().getContent()));
		for (String s = reader.readLine(); s != null; s = reader.readLine()) {
			builder.append(s);
		}
		result = builder.toString();
		// Log.d(TAG, "result is ( " + result + " )");

		// store cookie
		sCookieStore = (CookieStore) ((AbstractHttpClient) httpClient)
				.getCookieStore();
		return result;
	}

}